package com.etc;

import com.sun.javafx.robot.FXRobotImage;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.TabableView;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.sql.Time;
import java.util.*;
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 游戏主窗口
 * <p>
 * JPanel 面板
 * JFrame 框架
 */
public class AircraftwarGame extends JPanel {

    //窗口宽
    public static final int WIDTH = 400;
    //窗口高
    public static final int HEIGHT = 654;

    // 敌机图片
    public static BufferedImage airplane;
    // 小蜜蜂图片
    public static BufferedImage bee;
    // 背景图片
    public static BufferedImage background;
    // 子弹图片
    public static BufferedImage bullet;
    // 飞机图片
    public static BufferedImage hero0;
    // 飞机图片
    public static BufferedImage hero1;

    //英雄机对象
    public Hero hero = new Hero();
    // 敌机+小蜜蜂
    private FlyingObject[] flyings = {};
    //子弹数组
    private Bullet[] bullets = {};
    //得分
    int score = 0;


    //构造方法
    public AircraftwarGame() {
        //删除
//        flyings = new FlyingObject[2];
//        flyings[0] = new Airplane();
//        flyings[1] = new Bee();
//        bullets = new Bullet[1];
//        bullets[0] = new Bullet(100, 200);
    }

    //静态代码块，初始化我们图片资源
    static {
        try {
            airplane = ImageIO.read(AircraftwarGame.class.getClassLoader().getResource("images/airplane.png"));
            bee = ImageIO.read(AircraftwarGame.class.getClassLoader().getResource("images/bee.png"));
            background = ImageIO.read(AircraftwarGame.class.getClassLoader().getResource("images/background.png"));
            bullet = ImageIO.read(AircraftwarGame.class.getClassLoader().getResource("images/bullet.png"));
            hero0 = ImageIO.read(AircraftwarGame.class.getClassLoader().getResource("images/hero0.png"));
            hero1 = ImageIO.read(AircraftwarGame.class.getClassLoader().getResource("images/hero1.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //系统调用
    @Override
    public void paint(Graphics g) {
        //画背景
        g.drawImage(background, 0, 0, null);
        //画英雄飞机
        this.printHero(g);
        //画子弹对象
        this.printBullet(g);
        //画敌人对象
        this.printAirplane(g);
        //画得分和生命
        this.printScore(g);
    }


    /**
     * 画英雄机
     *
     * @param g
     */
    private void printHero(Graphics g) {
        g.drawImage(hero.image, hero.x, hero.y, null);
    }

    /**
     * 画敌机
     *
     * @param g
     */
    private void printAirplane(Graphics g) {
        //遍历敌机
        for (FlyingObject f : flyings) {
            g.drawImage(f.image, f.x, f.y + 100, null);
        }
    }

    /**
     * 画子弹
     *
     * @param g
     */
    private void printBullet(Graphics g) {
        for (Bullet bullet1 : bullets) {
            g.drawImage(bullet1.image, bullet1.x, bullet1.y, null);
        }
    }

    /**
     * 画分数和画命
     *
     * @param g
     */
    private void printScore(Graphics g) {
        //设置颜色
        g.setColor(new Color(0xF00000));
        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
        //画得分
        g.drawString("得分:" + score, 10, 25);
        //画飞机生命值
        g.drawString("生命:" + hero.getLife(), 10, 50);
    }


    /**
     * 随机生成敌人对象（敌机 小蜜蜂）
     */
    public static FlyingObject nextOne() {
        Random random = new Random();
        // 生成随机数【0-20】
        int i = random.nextInt(20);
        if (i == 0) {
            return new Bee();
        } else {
            return new Airplane();
        }
    }


    /**
     * 游戏方法主入口
     *
     * @param args
     */
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("飞机大战");
        AircraftwarGame aircraftwarGame = new AircraftwarGame();
        //将面板添加到窗口中
        jFrame.add(aircraftwarGame);
        jFrame.setSize(WIDTH, HEIGHT);
        //总是居顶
        jFrame.setAlwaysOnTop(true);
        // 设置默认关闭操作
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置中心点
        jFrame.setLocationRelativeTo(null);
        //设置窗口可见
        jFrame.setVisible(true);
        aircraftwarGame.action();

    }

    //声明定时器对象
    Timer timer;
    // 定时器的时间间隔已毫秒
    private int intervel = 10;

    public void action() {
        //鼠标监听
        MouseAdapter mouseAdapter = new MouseAdapter() {
            /**
             * 鼠标移动事件
             * @param e
             */
            @Override
            public void mouseMoved(MouseEvent e) {
//                System.out.println(e.getX());
//                System.out.println(e.getY());
                hero.moveTo(e.getX(),e.getY());
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
            }
        };
        //键盘事件

        KeyAdapter keyAdapter = new KeyAdapter() {
            //键盘按下去的方法
            @Override
            public void keyPressed(KeyEvent e) {
                switch (e.getKeyCode()){
                    case 38:
                        hero.y-= 10;
                        break;
                    case 40:
                        hero.y+= 10;
                        break;
                    case 37:
                        hero.x-= 10;
                        break;
                    case 39:
                        hero.x+= 10;
                        break;
                    default:
                        break;
                }
            }
        };


        //处理鼠标事件
        this.addMouseListener(mouseAdapter);
        this.addKeyListener(keyAdapter);
        this.requestFocus(true);
        this.addMouseMotionListener(mouseAdapter);

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //敌机入场
                enterAction();
                // 走一步
                stepAction();
                //发射子弹
                shootAction();
                //所有子弹与敌人的碰撞
                bangAction();
                //删除出界飞行物
                outOfBoundsAction();


                //重画
                repaint();
            }


        }, intervel, intervel);
    }

    /**
     * 敌机入场
     */
    //敌人入场次数
    int flyEnteredIndex = 0;

    public void enterAction() {
        // 每10毫秒加一次
        flyEnteredIndex++;
        //每400毫秒走一次
        if (flyEnteredIndex % 40 == 0) {
            FlyingObject o = nextOne();
            // 给数组扩容1个位置
            flyings = Arrays.copyOf(flyings, flyings.length + 1);
            //将随机飞行物放到数组中
            flyings[flyings.length - 1] = o;
        }
    }


    /**
     * 走一步
     */
    public void stepAction() {
        hero.step();
        // 敌机和小蜜蜂走
        for (FlyingObject flying : flyings) {
            flying.step();
        }
        // 子弹要走
        for (Bullet b : bullets) {
            b.step();
        }

    }


    /**
     * 游戏机发射子弹 子弹入场
     */
    int shootIndex = 0;

    public void shootAction() {
        shootIndex++;
        // 30  60  90 120 150
        if (shootIndex % 30 == 0) {
            Bullet[] shoot = hero.shoot();
            //给子弹的数组进行扩容
            bullets = Arrays.copyOf(this.bullets, bullets.length + shoot.length);
            //　　原数组   从元数据的起始位置开始　 目标数组 目标数组的开始起始位置  要copy的数组的长度
            System.arraycopy(shoot, 0, bullets, bullets.length - shoot.length, shoot.length);
        }
    }


    /**
     * 检查子弹是否在敌人的面积中
     */
    private void bangAction() {
        for (Bullet b : bullets) {

            bang(b);

        }
    }


    /**
     * 一发子弹 所有敌人的碰撞
     * @param b
     */
    private  void bang(Bullet b){

        int index = -1;
        for (int i = 0; i < flyings.length; i++) {
            FlyingObject flying = flyings[i];
            if (flying.shootBy(b)){
                index = i;
            }
        }

        if (index != -1){
            FlyingObject one = flyings[index];
            if (one instanceof Enemy){
                Enemy enemy = (Enemy)one;
                score+=enemy.getScore();
            }
            if (one instanceof Award){
                Award enemy = (Award)one;
                int type = enemy.getType();
                switch (type){
                    case Award.DOUBLE_FIRE:
                        hero.setDoubleFire(hero.getDoubleFire() + 40);
                        break;
                    case Award.LIFE:
                        hero.setLife(hero.getLife()+1);
                        break;
                    default:
                        break;
                }
            }

            //就是删除碰撞的那个飞行物
            FlyingObject flying = flyings[index];
            //把数据最后一个位置的飞行物放入 ， 撞击了的下标位置上
            flyings[index] = flyings[flyings.length -1];
            //吧撞击飞行物放入数组的最后一个位置
            flyings[flyings.length -1] = flying;
            //删除飞行物数组中的被撞机
            flyings =  Arrays.copyOf(flyings,flyings.length -1);
        }

    }


    /**
     * 越界的飞行物清除
     */
    public void outOfBoundsAction(){

        //越界飞行物
        FlyingObject[] flyingLives = new FlyingObject[flyings.length];//活着的
        int index = 0;
        for (int i = 0; i < flyings.length; i++) {
            FlyingObject flying = flyings[i];
            if (!flying.outBounds()){
                flyingLives[index] = flying;
                index++;
            }
        }
        flyings = Arrays.copyOf(flyingLives,index);


        Bullet[] bullets2 = new Bullet[bullets.length];//活着的
        index = 0;
        for (int i = 0; i < bullets.length; i++) {
            Bullet bullet = bullets[i];
            if (!bullet.outBounds()){
                bullets2[index] = bullet;
                index++;
            }
        }
        bullets = Arrays.copyOf(bullets2,index);





    }
}
